package com.leboncoin.batch;

import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;


import com.leboncoin.bean.SearchItemBean;
import com.leboncoin.bean.SubscriptionBean;
import com.leboncoin.xml.ConfigManager;

public class FullSearch {
	
    	protected static final Logger logger = Logger.getLogger(FullSearch.class.getName());	

	public static void main(String... args) throws Exception {
            ConfigManager.getInstance("conf/fullSearch.xml");
            testSearch();
	}

	public static void testSearch() throws Exception {
		
            for (SubscriptionBean subscriptionBean : ConfigManager.getInstance(null).getSubscriptions()) {
                CommonSearch commonSearch = CommonSearch.getInstance();
                commonSearch.searchFromSubscription(false, subscriptionBean);
                EntityManagerFactory emf = null;
                EntityManager em = null;
                EntityTransaction transac = null;
                try {
                    emf = Persistence.createEntityManagerFactory("leboncoin");
                    em = emf.createEntityManager();
                    transac = em.getTransaction();
                    transac.begin();

                    for (SearchItemBean searchItemBean:subscriptionBean.getSearchItems()){
                        em.merge(searchItemBean);
                    }


                    transac.commit();
                } catch (Exception e){
                    logger.severe(e.getMessage());
                    if (e.getCause() != null){
                        logger.severe(e.getCause().getMessage());
                    }
                    if (transac != null && transac.isActive()) transac.rollback();
                } finally {
                    if (em != null) em.close();
                    if (emf != null) emf.close();
                }
            }
		
	}

}
